from django.http import HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.paginator import Paginator

def common_search(request, kind, search_url, formClass, modelClass, template, filter_objects):
    form = formClass(request.GET)

    paginator = None
    page_obj = None
    result_count = 0

    if request.GET and form.is_valid():
        result_list = modelClass.objects.all()
        result_list = filter_objects(form, result_list)
        result_count = result_list.count()

        PAGINATE_BY = 100
        paginator = Paginator(result_list, PAGINATE_BY)

        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1

        try:
            page_obj = paginator.page(page)
        except (EmptyPage, InvalidPage):
            page_obj = paginator.page(paginator.num_pages)

        if request.GET.has_key('delete'):
            if not request.user.has_perm("browsertests.delete_result"):
                return HttpResponseForbidden("Deletion denied")
            # XXX should use DELETE FROM for better perf
            for result in result_list:
                result.delete()
            result_list = []

    extra_query = request.GET.copy()
    if "page" in extra_query:
        del extra_query["page"]
    extra_query = extra_query.urlencode()

    return render_to_response(template, {
        'kind': kind,
        'search_url': search_url,
        'form': form,
        'result_count': result_count,
        'paginator': paginator,
        'page_obj': page_obj,
        'extra_query': extra_query,
    },
    context_instance=RequestContext(request))
